package com.example.rxohosaudio;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@SuppressWarnings({"unused", "WeakerAccess"})
public final class RxAmplitude {
    static final String TAG = "RxAmplitude";
    private static HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, TAG);

    // on i9300, max value is 16385
    static final int AMPLITUDE_MAX_VALUE = 16385;
    static final int AMPLITUDE_MAX_LEVEL = 8;

    private static final int DEFAULT_AMPLITUDE_INTERVAL = 200;

    private final SecureRandom mRandom;

    private RxAmplitude() {
        mRandom = new SecureRandom();
    }

    public static Observable<Integer> from(@NonNull final AudioRecorder audioRecorder) {
        return from(audioRecorder, DEFAULT_AMPLITUDE_INTERVAL);
    }

    public static Observable<Integer> from(@NonNull final AudioRecorder audioRecorder,
                                           final long interval) {
        return new RxAmplitude().start(audioRecorder, interval);
    }

    private Observable<Integer> start(@NonNull final AudioRecorder audioRecorder, final long interval) {
        return Observable.interval(interval, TimeUnit.MILLISECONDS)
                .map(new Function<Long, Integer>() {
                         @Override
                         public Integer apply(@NonNull final Long aLong) throws Exception {
                             int amplitude;
                             try {
                                 amplitude = audioRecorder.getMaxAmplitude();
                             } catch (RuntimeException e) {
                                 HiLog.warn(label, " getMaxAmplitude fail:" + e.getMessage());
                                 amplitude = mRandom.nextInt(AMPLITUDE_MAX_VALUE);
                             }
                             amplitude = amplitude / (AMPLITUDE_MAX_VALUE / AMPLITUDE_MAX_LEVEL);
                             return amplitude;
                         }
                     }
                );
    }

    public static int getAmplitudeValue(final AudioRecorder audioRecorder) {
        int maxAmplitude = audioRecorder.getMaxAmplitude();
        HiLog.error(label, "maxAmplitude" + maxAmplitude);
        return maxAmplitude / (AMPLITUDE_MAX_VALUE / AMPLITUDE_MAX_LEVEL);
    }

}
